package com.dyh.quickdemo.lock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/*
@Author=Joey Wheeler
@Date=2021/3/29 11:27
*/
public class JavaLocalBizLock {
    private static  volatile  Map<String, ReentrantLock> lockMap = new HashMap<>();
    private static final Object nullLock = new Object();

   private static Logger logger = LoggerFactory.getLogger(JavaLocalBizLock.class);

    public static boolean tryLock(String bizKey,long time) throws InterruptedException {
        ReentrantLock reentrantLock = lockMap.get(bizKey);
        if (reentrantLock==null){
            synchronized (nullLock){
                if (reentrantLock==null){
                    reentrantLock = new ReentrantLock();
                    lockMap.put(bizKey,reentrantLock);
                    return reentrantLock.tryLock(time, TimeUnit.MILLISECONDS);
                }
                return reentrantLock.tryLock(time, TimeUnit.MILLISECONDS);
            }
        }
        return reentrantLock.tryLock(time,TimeUnit.MILLISECONDS);
    }

    public static void unlock(String bizKey){
        ReentrantLock reentrantLock = lockMap.get(bizKey);
        if (reentrantLock!=null){
            reentrantLock.unlock();
            lockMap.remove(bizKey);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new Thread(()->{
            try {
                logger.info("{} {}",
                        Thread.currentThread().getName(),
                        JavaLocalBizLock.tryLock("hello",100L));
                Thread.sleep(500L);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                JavaLocalBizLock.unlock("hello");
            }
        }).start();




        new Thread(()->{
            try {
                logger.info("{} {}",
                        Thread.currentThread().getName(),
                        JavaLocalBizLock.tryLock("hello",100L));
                Thread.sleep(500L);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                JavaLocalBizLock.unlock("hello");
            }
        }).start();
    }
}
